package com.crk.shixiguanli.service.impl;

import com.crk.shixiguanli.dao.*;
import com.crk.shixiguanli.entity.*;
import com.crk.shixiguanli.service.StudentService;
import com.crk.shixiguanli.service.UserService;
import com.crk.shixiguanli.util.IdCardGenerator;
import com.crk.shixiguanli.util.Page;
import com.crk.shixiguanli.util.ResponseResult;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Description:
 *
 * @author:
 * Date: 2020-04-02
 * Time: 15:59
 */
@Service
public class StudentServiceImpl implements StudentService {
    @Autowired
    StudentDao studentDao;
    @Autowired
    UserService userService;

    @Autowired
    RoleAuthDao roleAuthDao;
    @Autowired
    RoleDao roleDao;


    @Transactional
    @Override
    public ResponseResult upload(MultipartFile file) {
        try {
            InputStream is = file.getInputStream();
            Workbook wb = null;
            boolean isExcel2003 = true;
            String fileName = file.getOriginalFilename();
            if (fileName.matches("^.+\\.(?i)(xlsx)$")) {
                isExcel2003 = false;
            }
            if (isExcel2003) {
                wb = new HSSFWorkbook(is);
            } else {
                wb = new XSSFWorkbook(is);
            }
            Sheet sheet = wb.getSheetAt(0);

            for (int r = 1; r <= sheet.getLastRowNum(); r++) {
                Row row = sheet.getRow(r);
                if (row == null){
                    continue;
                }
                row.getCell(0).setCellType(Cell.CELL_TYPE_STRING);
                row.getCell(2).setCellType(Cell.CELL_TYPE_STRING);
//                学生编号
                String studentCode = row.getCell(0).getStringCellValue();
//                学生姓名
                String studentName = row.getCell(1).getStringCellValue();
//                身份证号
                String idCard = row.getCell(2).getStringCellValue();
//                所在学院
                String college = row.getCell(3).getStringCellValue();
//                所在专业
                String professional = row.getCell(4).getStringCellValue();
//                所在班级
                String className = row.getCell(5).getStringCellValue();
//                层次
                String level = row.getCell(6).getStringCellValue();
//                省份
                String province = row.getCell(7).getStringCellValue();
//                出生日期
                Date birthday = row.getCell(8).getDateCellValue();
//                性别
                String gender = row.getCell(9).getStringCellValue();
//                民族
                String nation = row.getCell(10).getStringCellValue();



                Student student = new Student();
                student.setStudentCode(studentCode);
                student.setStudentName(studentName);
                student.setIdCard(idCard);
                student.setCollege(college);
                student.setClassName(className);
                student.setCollege(college);
                student.setProfessional(professional);
                student.setClassName(className);
                student.setProvince(province);
                student.setLevel(level);
                student.setGender(gender);
                student.setBirthday(birthday);
                student.setNation(nation);


                Student studentByIdCard = studentDao.getStudentByIdCard(student.getIdCard());
                if (studentByIdCard != null){
                    continue;
                }
                studentDao.insert(student);
        }

        }catch (Exception e){
            e.printStackTrace();
            return ResponseResult.fail();
        }

        return ResponseResult.success();
    }



    @Override
    public ResponseResult batchSaveCollege(Set<String> collegeSet) {
        try {
            studentDao.batchSaveCollege(collegeSet);
            return ResponseResult.success();
        }catch (Exception e){
            e.printStackTrace();
            return ResponseResult.fail();
        }
    }

    @Override
    public ResponseResult batchSaveProfessional(List<Professional> professionalList) {
        try {
            System.out.println(professionalList);
            if (!professionalList.isEmpty()){
                studentDao.batchSaveProfessional(professionalList);
            }
            return ResponseResult.success();
        }catch (Exception e){
            e.printStackTrace();
            return ResponseResult.fail();
        }
    }

    /**
     * 查询学生列表-分页
     *
     * @param studentName  学生名称
     * @param college      学院名称
     * @param professional 专业名称
     * @param pageInfo     分页信息
     * @return
     */
    @Override
    public ResponseResult queryStudentPage(String studentName, String college
            , String professional, Page pageInfo) {
        Integer count = studentDao.countByCondition(studentName, college,professional);
        pageInfo.setAllRow(count);
        List<Student> studentList  = studentDao.selectByCondition(studentName, college,professional, pageInfo.getStart(), pageInfo.getSize());
        return ResponseResult.success(studentList);
    }

    @Override
    public ResponseResult getStaticByAge() {
        List<HashMap<String, Object>> staticByAge = studentDao.getStaticByAge();
        return getStatic(staticByAge);
    }

    @Override
    public ResponseResult getStaticByProvince() {
        List<HashMap<String, Object>> staticByProvince = studentDao.getStaticByProvince();

        return getStatic(staticByProvince);
    }

    @Override
    public ResponseResult getStaticByGender() {
        List<HashMap<String, Object>> staticByGender = studentDao.getStaticByGender();
        return getStatic(staticByGender);
    }

    @Override
    public ResponseResult getStaticByNation() {
        List<HashMap<String, Object>> staticByNation = studentDao.getStaticByNation();
        return getStatic(staticByNation);
    }

    private ResponseResult getStatic(List<HashMap<String, Object>> dataList){
        List<String> legend  = new ArrayList<>();
        List<HashMap<String,Object>> result = new ArrayList<>();
        for (HashMap<String, Object> map : dataList) {
            String name = map.get("name").toString();
            Integer count = Integer.parseInt(map.get("count").toString());
            HashMap<String,Object> newMap = new HashMap<>();
            newMap.put("name",name);
            newMap.put("value",count);
            result.add(newMap);
            if (legend.isEmpty() || !legend.contains(name)){
                legend.add(name);
            }
        }
        HashMap<String,Object> data = new HashMap<>();
        data.put("legend",legend);
        data.put("result",result);
        return ResponseResult.success(data);
    }

    @Override
    public User getStudentUserByIdCard(String idCard) {
        Student studentByIdCard = studentDao.getStudentByIdCard(idCard);
//        若存在对应的学生
        if (null != studentByIdCard){
            User userByIdCard = userService.getUserByIdCard(idCard);
            if (null != userByIdCard){
                return userByIdCard;
            }else{
                User newUser = new User();
                newUser.setUserName(studentByIdCard.getStudentName());
                newUser.setStatus((short)1);
                newUser.setIdCard(studentByIdCard.getIdCard());
                ResponseResult responseResult = userService.saveUser(newUser);
                if (ResponseResult.isSuccess(responseResult)){
                    userByIdCard = userService.getUserByIdCard(idCard);
                    //            分配角色
                    saveStudentRoleAuth(userByIdCard.getId());
                }
                return userByIdCard;
            }
        }else{
            return null;
        }
    }

    @Override
    public ResponseResult saveStudentBaseInfo(StudentDto studentDto) {
        User user = (User) SecurityUtils.getSubject().getPrincipal();
        String idCard = user.getIdCard();
        User userByIdCard = userService.getUserByIdCard(idCard);
        userByIdCard.setEmail(studentDto.getEmail());
        userByIdCard.setPhone(studentDto.getPhone());
        ResponseResult responseResult = userService.saveUser(userByIdCard);
        if (ResponseResult.isSuccess(responseResult)){
            Student studentByIdCard = studentDao.getStudentByIdCard(idCard);
            studentByIdCard.setBirthday(studentDto.getBirthday());
            studentByIdCard.setNation(studentDto.getNation());
            int updateByPrimaryKey = studentDao.updateByPrimaryKey(studentByIdCard);
            if (updateByPrimaryKey > 0){
                return ResponseResult.success();
            }else {
                return ResponseResult.fail();
            }
        }else{
            return ResponseResult.fail();
        }
    }

    private void saveStudentRoleAuth(Integer userId){
        RoleAuth roleAuth = new RoleAuth();
        roleAuth.setPartyId(userId);
        roleAuth.setPartyType((short)1);
        Role student = roleDao.getRoleByCode("student");
        roleAuth.setRoleId(student.getId());
        roleAuth.setCreateTime(new Date());
        roleAuth.setUpdateTime(new Date());
        roleAuth.setCreator(1);
        roleAuth.setUpdator(1);
        roleAuth.setStatus((short)1);
        roleAuthDao.insert(roleAuth);
    }




    @Override
    public ResponseResult confirmStudentInfo() {
        User user = (User) SecurityUtils.getSubject().getPrincipal();
        String idCard = user.getIdCard();
        Integer status = 2;
        studentDao.updateStudentStatus(idCard,status);
        return ResponseResult.success();
    }

    /**
     * 保存数据
     *
     * @param student
     * @return
     */
    @Override
    public ResponseResult saveStudent(Student student) {
        if (StringUtils.isEmpty(student.getId())){
            studentDao.insert(student);
        }else{
            studentDao.updateByPrimaryKey(student);
        }
        return ResponseResult.success();
    }

    @Override
    public ResponseResult getStudent(int id) {
        Student student = studentDao.selectByPrimaryKey(id);
        return ResponseResult.success(student);
    }

    @Override
    public ResponseResult deleteStudent(int id) {
        studentDao.deleteByPrimaryKey(id);
        return ResponseResult.success();
    }
}
